#include "Column_string.h"


Column_string::Column_string(const string& nm, const bool& null_is_ok, stringstream in_dat)
{
	name = nm;
	null_ok = null_is_ok;
	valid_cond.push_back(EQ);

	string temp;
	in_dat >> temp;
	while(! in_dat.fail())
	{
		if("null" == temp)
		{
			data.push_back(NULL);
		}
		else
		{
			data.push_back(new string(temp));
		}
		in_dat >> temp;
	}
}

Column_string::~Column_string(void)
{
	for(vector<string*>::const_iterator it = data.begin(); it != data.end(); ++it)
	{
		if(*it != NULL)
		{
			delete *it;
		}
	}
}


stringstream Column_string::select() const
{
	stringstream ret;
	for(vector<string*>::const_iterator it = data.begin(); it != data.end(); ++it)
	{
		if(it != data.begin()) ret << ' ';
		if(NULL == *it)
		{
			ret << "null";
		}
		else
		{
			ret << *(*it);
		}
	}
	return ret;
}


stringstream Column_string::select(const vector<int>& l) const
{
	stringstream ret;
	for(vector<int>::const_iterator it = l.begin(); it!=l.end(); ++it)
	{
		if(it!=l.begin())
		{
			ret << " ";
		}
		if(data[*it] == NULL)
		{
			ret << "null";
		}
		else
		{
			ret << *(data[*it]);
		}
	}
	return ret;
}

vector<int> Column_string::select_list() const
{
	vector<int> ret;
	string* elem = Validator::get_pointer<string>(null_ok);
	Cond_type cond = Validator::get_cond(true);

	for(vector<string*>::const_iterator it = data.begin(); it != data.end(); ++it)
	{
		if(elem != NULL && *it != NULL)
		{
			if((*elem == *(*it) && cond == EQ))
			{
				ret.push_back(it-data.begin());
			}
		}
		else
		{
			if((elem == NULL && *it == NULL && cond == EQ))
			{
				ret.push_back(it-data.begin());
			}
		}
	}

	if(elem != NULL) delete elem;

	return ret;
}

void Column_string::del()
{
	for(vector<string*>::const_iterator it = data.begin(); it != data.end(); ++it)
	{
		if(*it != NULL)
		{
			delete *it;
		}
	}
	data.clear();
}


void Column_string::del(const vector<int>& l)
{
	int we = 0;
	for(vector<int>::const_iterator it = l.begin(); it != l.end(); ++it)
	{
		if(data[(*it)-we] != NULL)
		{
			delete data[(*it)-we];
		}
		data.erase(data.begin() + (*it) - we);
		++we;
	}
}

void Column_string::insert()
{
	string msg = "[" + name + "] (string" + ((null_ok) ? "/null" : "") + "): ";
	string* elem = Validator::get_pointer<string>(null_ok, msg);

	data.push_back(elem);
}


string Column_string::get_type_name() const
{
	return "s";
}

int Column_string::get_size() const
{
	return data.size();
}